package com.sangeng.controller;

import com.alibaba.fastjson.JSON;
import com.sangeng.domain.ResponseResult;
import com.sangeng.domain.User;
import com.sangeng.mapper.TestMapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Hanson
 * @date 2022/11/21 17:21
 */
@RestController
public class TestController {

    @Resource
    private TestMapper testMapper;

    @PostMapping("/user/test")
    public void test(HttpServletRequest request, HttpServletResponse response, @RequestBody User user){
        //登录
        String userName = user.getUserName();
        List<String> list = testMapper.selectPermsByUserUserName(userName);

        String id = request.getSession().getId();
        request.getSession().setAttribute(id,list);
        Map<String,String> map = new HashMap<>();
        map.put("sessionID",id);
        try {
            response.getWriter().write(JSON.toJSONString(map));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @GetMapping("/get_all")
    public Map<String, Object> getAll(HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        // 遍历
        for (Enumeration<String> enumeration = session.getAttributeNames();
             enumeration.hasMoreElements();) {
            String key = enumeration.nextElement();
            Object value = session.getAttribute(key);
            result.put(key, value);
        }
        // 返回
        return result;
    }

    @GetMapping("/get_one")
    public Map<String, Object> getOne (HttpSession session) {
        Map<String, Object> result = new HashMap<>();
//        // 遍历
//        for (Enumeration<String> enumeration = session.getAttributeNames();
//             enumeration.hasMoreElements();) {
//            String key = enumeration.nextElement();
//            Object value = session.getAttribute(key);
//            result.put(key, value);
//        }
        String key = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI2MjFjMTA1NWNjZmI0YjIwYTNkZmZlOGNjNzAxY2Q3NiIsInN1YiI6IjIiLCJpc3MiOiJzZyIsImlhdCI6MTY2OTA4MDg5MiwiZXhwIjoxNjY5MDg0NDkyfQ.QgDuEgPzBNrRKm7hU-3_ru17vK8zFDXejzkCLulz0XA";
        Object value = session.getAttribute(key);
        result.put(key,value);
        // 返回
        return result;
    }
}
